<?php
/**
 * Main function that routes all requests to appropiate controller
 * 
 * @author: Victor Nava
 * @return unknown_type
 */
//Development error config
//error_reporting(E_ALL);

//Production error config
ini_set('display_errors', 0);

include 'db.php';
include 'util.php';
include 'html.php';
include '.php';

define('DEFAULT_CONTROLLER', 'offer_controller');
define('HOME_PAGE', 'router.php');

main();
exit();

/**
 * 
 * Main function called everytime a request is made
 * 
 * Special letters in requests
 * c = controller name
 * a = controller action
 * f = reply format: html (default) or json;
 */
function main(){

	session_start();
	//print_r($_SESSION);

	//if no controller specified load default controller
	if(isset($_REQUEST['c'])){
		//get controller name
		$controllerName = $_REQUEST['c']."_controller";

		//get controller instance
		$controller = getController($controllerName);

		//get controller action (method)
		$action  = isset($_REQUEST['a']) ? $_REQUEST['a'] : "index";

		//if there no method in controller for action show error
		if(!method_exists($controller, $action)){
			echo "Method $action not found in $controllerName";
			return;
		}	
	}
	//load default controller with index action
	else{
		$controller = getController(DEFAULT_CONTROLLER);
		$action = "index";
	}
	$controller->request = getRequest();
	
	$_SESSION['referer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : HOME_PAGE;
	
	//call controller method;
	$controller->$action();
}

/**
 * Helpler for accesing the request
 * Encapsulates both GET and POST request into a single method
 *  
 * @return Array request
 */
function getRequest(){
	$request = false;

	if ($_SERVER['REQUEST_METHOD'] == 'GET'){
		$request = $_GET;
	}
	else if ($_SERVER['REQUEST_METHOD'] == 'POST'){
		$request = $_POST;
	}
	//echo $request;
	return $request;
}

/**
 * Returns the controller instance based on the controller name
 * 
 * @param $controllerName
 * @return Controller object
 */
function getController($controllerName){
	$file = "$controllerName.php";

	if(!is_readable("$file")){
		//TODO render error view
		echo "controller file: $file not found";
		exit();
	}

	//load the controller file;
	include($file);

	if(!class_exists($controllerName)){
		//TODO render error view
		echo "controller class: $controllerName not found";
		exit();
	}
	//construct controller
	return new $controllerName();
}
?>